import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { Controller, type SubmitHandler, useForm } from "react-hook-form"

import {
  Button,
  Combobox,
  DialogActionTrigger,
  DialogTitle,
  HStack,
  Input,
  Portal,
  RadioGroup,
  Text,
  useFilter,
  useListCollection,
  VStack,
} from "@chakra-ui/react"
import { useEffect, useState } from "react"
import { FaPlus } from "react-icons/fa"

import { DeviceService, ProjectPublic, ProjectsService } from "@/client"
import type { ApiError } from "@/client/core/ApiError"
import useCustomToast from "@/hooks/useCustomToast"
import { handleError } from "@/utils"
import {
  DialogBody,
  DialogCloseTrigger,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
  DialogTrigger,
} from "../ui/dialog"
import { Field } from "../ui/field"


type TaskCreate = {
  taskName: string
  overwrite: boolean
  executeNum: number
  projectName: string
  projectId: string
}

const AddTask = ({ device_id, scripts }: { device_id: number, scripts: string[] }) => {
  const [isOpen, setIsOpen] = useState(false)
  const queryClient = useQueryClient()
  const { showSuccessToast } = useCustomToast()
  const {
    register,
    handleSubmit,
    reset,
    control,
    formState: { errors, isValid, isSubmitting },
  } = useForm<TaskCreate>({

    mode: "onBlur",
    criteriaMode: "all",
    defaultValues: {
      taskName: "在线任务下发",
      overwrite: true,
      executeNum: 1,
      projectName: '',
    },
  })

  const { data } = useQuery({
    queryKey: ["getProjects"],
    queryFn: async () => {
      return await ProjectsService.getProjects()
    }
  })
  const { contains } = useFilter({ sensitivity: "base" })

  const { collection, filter, set } = useListCollection<ProjectPublic>({
    initialItems: data?.data ?? [],
    filter: contains,
    itemToString(item) {
      return item.name ?? ''
    },
    itemToValue(item) {
      return item.id ?? ''
    },
  })

  useEffect(() => {
    if (data) {
      console.log(data)
      set(data.data)
    }
  }, [data])

  const mutation = useMutation({
    mutationFn: (data: TaskCreate) => {
      console.log(data)
      return DeviceService.batchExexuteScripts({ deviceId: device_id, requestBody: { info: { overwrite: `${data.overwrite}`, num: `${data.executeNum}`, name: data.taskName, user_id: JSON.parse(localStorage.getItem("currentUser")).id, project_name: data.projectName }, scripts: scripts } })
    }
    ,
    onSuccess: () => {
      showSuccessToast("任务创建成功.")
      reset()
      setIsOpen(false)
    },
    onError: (err: ApiError) => {
      handleError(err)
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["addTask"] })
    },
  })

  const onSubmit: SubmitHandler<TaskCreate> = (data) => {
    mutation.mutate(data)
  }

  return (
    <DialogRoot
      size={{ base: "xs", md: "md" }}
      placement="center"
      open={isOpen}
      onOpenChange={({ open }) => setIsOpen(open)}
    >
      <DialogTrigger asChild>
        <Button value="add-item" my={4}>
          <FaPlus fontSize="16px" />
          创建任务
        </Button>
      </DialogTrigger>
      <DialogContent>
        <form onSubmit={handleSubmit(onSubmit)}>
          <DialogHeader>
            <DialogTitle>创建任务</DialogTitle>
          </DialogHeader>
          <DialogBody>
            <Text mb={4}>请填写任务详情.</Text>
            <VStack gap={4}>
              <Field
                required
                invalid={!!errors.taskName}
                errorText={errors.taskName?.message}
                label="任务名"
              >
                <Input
                  id="taskName"
                  {...register("taskName", {
                    required: "请填写任务名.",
                  })}
                  placeholder="任务名"
                  type="text"
                />
              </Field >
              <Field
                invalid={!!errors.executeNum}
                errorText={errors.executeNum?.message}
                label="执行次数"
              >
                <Input
                  id="description"
                  {...register("executeNum", { required: "请填写执行次数." })}
                  placeholder="执行次数"
                  type="text"
                />
              </Field>
              <Field
                invalid={!!errors.projectName}
                errorText={errors.projectName?.message}
                label="项目"
              >
                <Controller
                  name="projectName"
                  control={control}
                  render={({ field }) => (
                    <Combobox.Root
                      collection={collection}
                      onInputValueChange={(e) => {
                        field.onChange(e.inputValue)
                        filter(e.inputValue)
                      }}
                      allowCustomValue

                    >
                      <Combobox.Control>
                        <Combobox.Input placeholder="Type to search" />
                        <Combobox.IndicatorGroup>
                          <Combobox.ClearTrigger />
                          <Combobox.Trigger />
                        </Combobox.IndicatorGroup>
                      </Combobox.Control>

                      <Portal >
                        <Combobox.Positioner style={{ zIndex: 9999 }}>
                          <Combobox.Content>
                            <Combobox.Empty>No items found</Combobox.Empty>
                            {collection.items.map((item) => (
                              <Combobox.Item item={item} key={item.id}>
                                {item.name}
                                <Combobox.ItemIndicator />
                              </Combobox.Item>
                            ))}
                          </Combobox.Content>
                        </Combobox.Positioner>
                      </Portal>
                    </Combobox.Root>
                  )} />
              </Field>
              <Field
                invalid={!!errors.overwrite}
                errorText={errors.overwrite?.message}
                label="是否覆盖测试结果"
              >
                <Controller
                  name="overwrite"
                  control={control}
                  render={({ field }) => (
                    <RadioGroup.Root
                      name={field.name}
                      onValueChange={({ value }) => {
                        field.onChange(value === 'true')
                      }}
                      value={field.value ? 'true' : 'false'}
                    >
                      <HStack gap="6">
                        <RadioGroup.Item key={'overwriteT'} value={'true'}>
                          <RadioGroup.ItemHiddenInput onBlur={field.onBlur} />
                          <RadioGroup.ItemIndicator />
                          <RadioGroup.ItemText>覆盖</RadioGroup.ItemText>
                        </RadioGroup.Item>
                        <RadioGroup.Item key={'overwriteF'} value={'false'}>
                          <RadioGroup.ItemHiddenInput onBlur={field.onBlur} />
                          <RadioGroup.ItemIndicator />
                          <RadioGroup.ItemText>不覆盖</RadioGroup.ItemText>
                        </RadioGroup.Item>
                      </HStack>
                    </RadioGroup.Root>
                  )}
                />
              </Field>
            </VStack>

          </DialogBody>

          <DialogFooter gap={2}>
            <DialogActionTrigger asChild>
              <Button
                variant="subtle"
                colorPalette="gray"
                disabled={isSubmitting}
              >
                取消
              </Button>
            </DialogActionTrigger>
            <Button
              variant="solid"
              type="submit"
              disabled={!isValid}
              loading={isSubmitting}
            >
              创建
            </Button>
          </DialogFooter>
        </form>
        <DialogCloseTrigger />
      </DialogContent>
    </DialogRoot>
  )
}

export default AddTask
